﻿using TjZheng.Controls;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;
using TjZheng.Framework;

namespace TjZheng.Example.MVC.Controllers
{
    public class QueryFilter : FilterAttribute, IActionFilter
    {
        public void OnActionExecuted(ActionExecutedContext filterContext)
        {

        }

        public void OnActionExecuting(ActionExecutingContext filterContext)
        {
            var objValueProvider = filterContext.Controller.ValueProvider;
            List<string> QueryConditionList = new List<string>();
            var objController = filterContext.Controller as Controller;
            if (!objValueProvider.ContainsPrefix("QueryInfo.Prefixs"))
            {
                filterContext.Controller.ViewBag.QueryCondition = string.Empty;
                return;
            }
            var objValueProviderResult = objValueProvider.GetValue("QueryInfo.Prefixs");
            foreach (var prefix in objValueProviderResult.RawValue as string[])
            {
                if (objValueProvider.ContainsPrefix(prefix))
                {
                    QueryInfo objQueryInfo = new QueryInfo();
                    //Predicate<string> propertyFilter = propertyName => BindAttribute.IsPropertyAllowed(propertyName, null, null);
                    IModelBinder objModelBinder = ModelBinders.Binders.GetBinder(typeof(QueryInfo));
                    ModelBindingContext objModelBindingContext = new ModelBindingContext()
                    {
                        ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(() => objQueryInfo, typeof(QueryInfo)),
                        ModelName = prefix,
                        ModelState = objController.ModelState,
                        //PropertyFilter = propertyFilter,
                        ValueProvider = objValueProvider
                    };
                    objModelBinder.BindModel(objController.ControllerContext, objModelBindingContext);
                    if (objController.ModelState.IsValid)
                    {
                        string condition = objQueryInfo.GetCondition();
                        if (condition.IsNoNull())
                        {
                            QueryConditionList.Add(condition);
                        }
                    }
                }
            }
            string QueryCondition = string.Empty;
            if (QueryConditionList.IsNoNull())
            {
                QueryCondition = QueryConditionList.Aggregate((x, y) => x + " AND " + y);
            }
            filterContext.Controller.ViewBag.QueryCondition = QueryCondition;
        }
    }
}